/**
 * Created by FreezeSoul on 2017/8/17.
 */
define(
    ["app/core/base",
        "app/core/util",
        "../echartsMeta",
        "jquery",
        "underscore",
        'JSONParse',
        'loglevel',
        "echarts"
    ],
    function (Chart, Util, Meta, $, _, JSON, log, ec) {

        var property = {
            name: '通用属性',
            config: "property",
            option: []
                .concat($.extend(true, [], Meta.titleProperties))
                .concat($.extend(true, [], Meta.legendProperties))
                .concat($.extend(true, [], Meta.tooltipProperties))
                .concat($.extend(true, [], Meta.toolboxProperties))
                .concat([
                    {
                        group: '其他',
                        id: 'b757a938-727f-4026-9d96-22c86e4ccb18',
                        name: '背景色',
                        enable: false,
                        type: 'color',
                        value: 'transparent',
                        default: 'transparent',
                        link: 'backgroundColor',
                        tooltip: '背景色，如需透明请填写:transparent'
                    },
                    {
                        group: '其他',
                        id: '9b9ed398-612a-454e-82a4-38ea5478c973',
                        name: '序列颜色',
                        enable: false,
                        type: 'colors',
                        value: [],
                        default: [],
                        data: [
                            '#FE8463', '#9BCA63', '#FAD860', '#60C0DD', '#0084C6',
                            '#D7504B', '#C6E579', '#26C0C0', '#F0805A', '#F4E001',
                            '#B5C334'
                        ],
                        link: 'color',
                        tooltip: '序列颜色会根据给出的颜色集合依次渲染'
                    },
                    {
                        group: '绑定',
                        id: '17994381-e1fe-4551-a852-a5a0571ed899',
                        name: '序列绑定',
                        enable: true,
                        type: 'seriesBinding',
                        dataset: '',
                        dimension: '',
                        measure: '',
                        tooltip: '序列绑定设置，绑定行数要与序列设置数量一致'
                    },
                    {
                        group: '绑定',
                        id: 'a320684c-8ca5-49f0-aab7-853e0fde9e5c',
                        name: '过滤列名称',
                        enable: false,
                        type: 'text',
                        value: '',
                        default: '',
                        tooltip: '绑定数据集，客户端过滤字段列名称'
                    },
                    {
                        group: '绑定',
                        id: '96f30ae6-6fe0-4faa-8b7f-a302a49a0434',
                        name: '过滤列默认值',
                        enable: false,
                        type: 'text',
                        value: '',
                        default: '',
                        tooltip: '绑定数据集，客户端过滤字段默认值'
                    },
                    {
                        group: '序列',
                        id: 'f53a0a43-6d1b-43e0-b514-122a8b155ece',
                        name: '序列',
                        type: 'group',
                        items: [],
                        option: [
                            {
                                id: 'f3f26cc8-3764-4f0a-8180-a9f88668420c',
                                name: '饼图半径设置',
                                enable: false,
                                type: 'text',
                                value: '0%,50%',
                                link: function (option) {
                                    var _this = this;
                                    var radius = ['0%', '50%']
                                    if (_this.enable) {
                                        var radiusArr = _this.value.split(',');

                                        if (radiusArr.length >= 2) {
                                            radius = $.parseJSON('["' + radiusArr[0] + '","' + radiusArr[1] + '"]');
                                        }
                                    }
                                    Util.setOption("radius", radius, option);
                                },
                                tooltip: '饼图显示面积的半径设置'
                            }
                        ],
                        link: 'series',
                        tooltip: '字段说明:<br/>分组控件，支持动态扩展，内部可增加支持的类型属性'
                    }
                ]).concat($.extend(true, [], Meta.otherProperties)),
            MapOption: function (option) {
                Util.linkOption(this.option, option);
            }
        };

        var pie = Chart.extend({
                constructor: function (layout) {
                    this._layout = layout;
                    this._lastdata = null;
                    this._container = null;
                    this._chart = null;
                    this._option = {
                        Binding: [],
                        Events: [],
                        Extend: $.extend(true, {}, property),
                        Option: {
                            tooltip: {
                                trigger: 'item',
                                formatter: function (params, ticket, callback) {
                                    if (params.name) {
                                        return params.seriesName + ": " + params.name + " - " + params.value * 100 + "%";
                                    }
                                    return null;
                                }
                            },
                            legend: {
                                top: "25%",
                                left: "25%",
                                itemHeight: 18,
                                data: ['实勘率', '户型图比例', '钥匙率', '委托率', '经理陪看率'],
                                textStyle: {
                                    color: '#fff'
                                },
                                selectedMode: true,
                                orient: "vertical"
                            },
                            series: [{
                                name: '实勘率',
                                type: 'pie',
                                clockWise: true, //顺时加载
                                hoverAnimation: false, //鼠标移入变大
                                radius: [180, 200],
                                itemStyle: {
                                    normal: {
                                        label: {
                                            show: false
                                        },
                                        labelLine: {
                                            show: false
                                        }
                                    }
                                },
                                label: {
                                    normal: {
                                        show: false,
                                        formatter: "{b}"
                                    }
                                },
                                data: [{
                                    value: 0.6,
                                    name: 0.6,
                                    itemStyle: {
                                        normal: {
                                            color: "#FE8463"
                                        }
                                    }
                                }, {
                                    value: 1 - 0.6,
                                    itemStyle: {
                                        normal: {
                                            color: 'transparent'
                                        }
                                    }
                                }]
                            }, {
                                name: '户型图比例',
                                type: 'pie',
                                clockWise: true, //顺时加载
                                hoverAnimation: false, //鼠标移入变大
                                radius: [155, 175],
                                itemStyle: {
                                    normal: {
                                        label: {
                                            show: false
                                        },
                                        labelLine: {
                                            show: false
                                        }
                                    }
                                },
                                label: {
                                    normal: {
                                        show: false,
                                        formatter: "{b}"
                                    }
                                },
                                data: [{
                                    value: 0.5,
                                    name: 0.5,
                                    itemStyle: {
                                        normal: {
                                            color: "#9BCA63"
                                        }
                                    }
                                }, {
                                    value: 1 - 0.5,
                                    itemStyle: {
                                        normal: {
                                            color: 'transparent'
                                        }
                                    }
                                }]
                            }, {
                                name: '钥匙率',
                                type: 'pie',
                                clockWise: true, //顺时加载
                                hoverAnimation: false, //鼠标移入变大
                                radius: [130, 150],
                                itemStyle: {
                                    normal: {
                                        label: {
                                            show: false
                                        },
                                        labelLine: {
                                            show: false
                                        }
                                    }
                                },
                                label: {
                                    normal: {
                                        show: false,
                                        formatter: "{b}"
                                    }
                                },
                                data: [{
                                    value: 0.4,
                                    name: 0.4,
                                    itemStyle: {
                                        normal: {
                                            color: "#FAD860"
                                        }
                                    }
                                }, {
                                    value: 1 - 0.4,
                                    itemStyle: {
                                        normal: {
                                            color: 'transparent'
                                        }
                                    }
                                }]
                            }, {
                                name: '委托率',
                                type: 'pie',
                                clockWise: true, //顺时加载
                                hoverAnimation: false, //鼠标移入变大
                                radius: [105, 125],
                                itemStyle: {
                                    normal: {
                                        label: {
                                            show: false
                                        },
                                        labelLine: {
                                            show: false
                                        }
                                    }
                                },
                                label: {
                                    normal: {
                                        show: false,
                                        formatter: "{b}"
                                    }
                                },
                                data: [{
                                    value: 0.6,
                                    name: 0.6,
                                    itemStyle: {
                                        normal: {
                                            color: "#60C0DD"
                                        }
                                    }
                                }, {
                                    value: 1 - 0.6,
                                    itemStyle: {
                                        normal: {
                                            color: 'transparent'
                                        }
                                    }
                                }]
                            }, {
                                name: '经理陪看率',
                                type: 'pie',
                                clockWise: true, //顺时加载
                                hoverAnimation: false, //鼠标移入变大
                                radius: [80, 100],
                                itemStyle: {
                                    normal: {
                                        label: {
                                            show: false
                                        },
                                        labelLine: {
                                            show: false
                                        }
                                    }
                                },
                                label: {
                                    normal: {
                                        show: false,
                                        formatter: "{b}"
                                    }
                                },
                                data: [{
                                    value: 0.3,
                                    name: 0.3,
                                    itemStyle: {
                                        normal: {
                                            color: "#0084C6"
                                        }
                                    }
                                }, {
                                    value: 1 - 0.3,
                                    itemStyle: {
                                        normal: {
                                            color: 'transparent'
                                        }
                                    }
                                }]
                            }],
                            color: [
                                "#FE8463",
                                "#9BCA63",
                                "#FAD860",
                                "#60C0DD",
                                "#0084C6",
                                "#D7504B",
                                "#C6E579",
                                "#26C0C0",
                                "#F0805A",
                                "#F4E001",
                                "#B5C334"
                            ]
                        }
                    };
                },
                init: function (element) {
                    try {
                        this._container = element;
                        this._chart = ec.init(element, null, {
                            renderer: 'canvas'
                        });
                        this._bindEvent();
                    } catch (e) {
                        log.error(e);
                    }
                },
                _bindEvent: function () {
                    var _this = this;
                    if (!this._filterDataHandle) {
                        this._filterDataHandle = function (params) {
                            _this.filterDataHandle.call(_this, params);
                        };
                    }
                    this._layout.removeListener("filterData", this._filterDataHandle);
                    this._layout.addListener("filterData", this._filterDataHandle);
                },
                filterDataHandle: function (params) {
                    var _this = this;
                    var flag = false;
                    var filterColumn = _.findWhere(_this._option.Extend.option, {name: '过滤列名称'});
                    var filterValue = _.findWhere(_this._option.Extend.option, {name: '过滤列默认值'});

                    if (filterColumn && filterValue
                        && filterColumn.enable && filterValue.enable
                        && filterColumn.value !== "" && filterValue.value !== ""
                    ) {
                        for (var prop in params) {
                            if (!params.hasOwnProperty(prop)) continue;
                            if (filterColumn.value === prop) {
                                filterValue.value = params[prop];
                                flag = true;
                            }
                        }
                    }
                    if (flag && _this._lastdata) {
                        _this.setData(_this._lastdata);
                    }
                },
                example: function () {
                    try {
                        this._chart.setOption(this._option.Option, true);
                    } catch (e) {
                        log.error(e);
                    }
                },
                _readProperty: function () {
                    try {
                        if (!this._option.Extend) return;
                        Util.deepMapOption(property, this._option.Extend, this._option.Option);
                    } catch (e) {
                        log.error(e);
                    }
                },
                _bindData: function (data) {
                    var tables = data;
                    var _this = this;
                    var seriesItems = _.findWhere(this._option.Extend.option, {type: 'group'});

                    //清除工作
                    if (seriesItems.items.length > 0) {
                        if (this._option.Option.legend) {
                            this._option.Option.legend.data = [];
                        }

                        var bindProperty = _.findWhere(this._option.Extend.option, {type: 'seriesBinding'});
                        if (!bindProperty) return;

                        var dataSetCode = bindProperty.dataset;
                        var dimensionCode = bindProperty.dimension.ColumnCode;
                        var measureCode = bindProperty.measure.ColumnCode;

                        if (dataSetCode && dimensionCode && measureCode) {
                            var table = tables[dataSetCode];
                            var binding = _.findWhere(_this._option.Binding, {DataSetCode: dataSetCode});
                            var dimension = _.findWhere(binding.Dimensions, {Code: dimensionCode}).Column;
                            var measure = _.findWhere(binding.Measures, {Code: measureCode}).Column;
                            var sumValue = 0;
                            $.each(table, function (j, row) {
                                sumValue += row[measure];
                            });
                            var colorList = [
                                "#FE8463",
                                "#9BCA63",
                                "#FAD860",
                                "#60C0DD",
                                "#0084C6",
                                "#D7504B",
                                "#C6E579",
                                "#26C0C0",
                                "#F0805A",
                                "#F4E001",
                                "#B5C334"
                            ];
                            if (_this._option.Option.color.length >= table.length) {
                                colorList = _this._option.Option.color;
                            }
                            table = _this._filterTable(_this._option.Extend.option, table);
                            var tableCopy = _.sortBy(table, measure).reverse();
                            $.each(tableCopy, function (j, row) {
                                if (_this._option.Option.legend && _this._option.Option.legend.data.indexOf(row[dimension]) === -1) {
                                    _this._option.Option.legend.data.push(row[dimension]);
                                }
                                var dataList = [];
                                if (_this._option.Option.series[j].data.length === 2) {
                                    dataList = _this._option.Option.series[j].data;
                                    dataList[0].value = (row[measure] / sumValue).toFixed(2);
                                    dataList[0].name = row[measure];
                                    if (!dataList[0].itemStyle)
                                        dataList[0].itemStyle = {};
                                    if (!dataList[0].itemStyle.normal)
                                        dataList[0].itemStyle.normal = {};
                                    dataList[0].itemStyle.normal.color = colorList[j];

                                    dataList[1].value = (1 - (row[measure] / sumValue)).toFixed(2);

                                    if (!dataList[1].itemStyle)
                                        dataList[1].itemStyle = {};
                                    if (!dataList[1].itemStyle.normal)
                                        dataList[1].itemStyle.normal = {};
                                    dataList[1].itemStyle.normal.color = "transparent";
                                } else {
                                    dataList.push(
                                        {
                                            "value": (row[measure] / sumValue).toFixed(2),
                                            "name": row[measure],
                                            "itemStyle": {
                                                "normal": {
                                                    "color": colorList[j]
                                                }
                                            }
                                        });
                                    dataList.push({
                                        "value": (1 - (row[measure] / sumValue)).toFixed(2),
                                        "itemStyle": {
                                            "normal": {
                                                "color": "transparent"
                                            }
                                        }
                                    });
                                }


                                if (_this._option.Option.series.length >= j + 1) {
                                    _this._option.Option.series[j].type = 'pie';
                                    _this._option.Option.series[j].name = row[dimension];
                                    _this._option.Option.series[j].data = dataList;
                                    _this._option.Option.series[j].clockWise = true;
                                    _this._option.Option.series[j].hoverAnimation = false;
                                } else {
                                    _this._option.Option.series.push({
                                        name: row[dimension],
                                        type: 'pie',
                                        clockWise: true,
                                        hoverAnimation: false,
                                        data: dataList
                                    });
                                }
                            });
                            if (_this._option.Option.series.length > table.length) {
                                _this._option.Option.series.splice(table.length, _this._option.Option.series.length - table.length)
                            }
                        }
                    }
                },
                _filterTable: function (option, table) {
                    var filterColumn = _.findWhere(option, {name: '过滤列名称'});
                    var filterValue = _.findWhere(option, {name: '过滤列默认值'});

                    if (filterColumn && filterValue
                        && filterColumn.enable && filterValue.enable
                        && filterColumn.value !== "" && filterValue.value !== ""
                    ) {
                        var tableCopy = _.map(table, _.clone);
                        return _.filter(tableCopy, function (row) {
                            return row[filterColumn.value] === filterValue.value;
                        });
                    }
                    return table;
                },
                setData: function (data) {
                    try {
                        this._lastdata = data;
                        this._readProperty();
                        if (data
                            && this._option.Binding
                            && this._option.Binding.length > 0
                            && this._option.Extend) {

                            this._bindData(data);

                            this._readProperty();
                        }
                        this._chart.setOption(this._option.Option, true);

                        //Util.setEChartsMeta(this, this._container, this._option.Extend.option);
                    } catch (e) {
                        log.error(e);
                    }
                }

                ,
                setOption: function (option) {
                    try {
                        return this._option = $.extend(true, {}, option);
                    } catch (e) {
                        log.error(e);
                    }
                }
                ,
                getOption: function () {
                    try {
                        this._readProperty();
                    } catch (e) {
                        log.error(e);
                    }
                    return this._option;
                }
                ,
                setTheme: function (theme) {
                    try {
                        this._chart.setTheme(theme);
                    } catch (e) {
                        log.error(e);
                    }
                }
                ,
                resize: function () {
                    try {
                        this._chart.resize();
                    } catch (e) {
                        log.error(e);
                    }
                }
                ,
                showLoading: function () {
                    try {
                        if (this._layout && this._layout.showLoading) {
                            this._layout.showLoading(this);
                        }
                    } catch (e) {
                        log.error(e);
                    }
                }
                ,
                hideLoading: function () {
                    try {
                        if (this._layout && this._layout.hideLoading) {
                            this._layout.hideLoading(this);
                        }
                    } catch (e) {
                        log.error(e);
                    }
                }
                ,
                dispose: function () {
                    try {
                        this._chart.dispose();
                        this._layout.removeListener("filterData", this._filterDataHandle);
                    } catch (e) {
                        log.error(e);
                    }
                }
                , getElement: function () {
                    return this._container;
                },
                getChart: function () {
                    return this._chart;
                }
            })
        ;

        return {
            Chart: pie,
            Property: property
        };
    })
;
